  #
# Copyright 2013 - Tom Alessi
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""This module contains all of the views for the Berper main
   application.  

"""


from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.db.models import Sum
from berper.main.models import Queue
from berper.main.models import Report
import datetime
import pytz


def index(request):
    """Default index page
    
    """

    # Obtain the queue of running scans
    queue = Queue.objects.values('name__name','name__site__site','start','report_uid').order_by('start')

    # Obtain the severity numbers
    now = datetime.datetime.today()
    date_to = now.strftime("%Y-%m-%d")

    # Move back 30 days
    then = datetime.timedelta(days=30)
    date_from = now - then
    date_from = date_from.strftime("%Y-%m-%d")
    
    # Add time information to the dates and the timezone (use the server's timezone)
    date_from += ' 00:00:00'
    date_from = datetime.datetime.strptime(date_from, '%Y-%m-%d %H:%M:%S')
    date_from = pytz.timezone(settings.TIME_ZONE).localize(date_from)

    date_to += ' 23:59:59'
    date_to = datetime.datetime.strptime(date_to, '%Y-%m-%d %H:%M:%S')
    date_to = pytz.timezone(settings.TIME_ZONE).localize(date_to)

    # Obtain severity information
    severity_info = Report.objects.filter(start__range=[date_from,date_to]).extra(
                                    {'start':"date(convert_tz(start,'%s','%s'))" % ('UTC',settings.TIME_ZONE)}
                                    ).values('start').annotate(Sum('severity__information'),Sum('severity__low'),Sum('severity__medium'),Sum('severity__high')).order_by('start')

    # Obtain Urls scanned and requests made information
    request_info = Report.objects.filter(start__range=[date_from,date_to]).extra(
                                    {'start':"date(convert_tz(start,'%s','%s'))" % ('UTC',settings.TIME_ZONE)}
                                    ).values('start').annotate(Sum('urls_scanned__urls'),Sum('requests_made__requests')).order_by('start')


    # Print the page
    return render_to_response(
       'main/index.html',
       {
          'title':'Berper | Home',
          'queue':queue,
          'request_info':request_info,
          'severity_info':severity_info

       },
       context_instance=RequestContext(request)
    )


